import React, { useState, useEffect } from 'react';
import { Card, Table, Button, Tag, Modal, Form, Input, DatePicker, Select, message, Space } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { getNotices, createNotice, updateNotice, deleteNotice } from '../../../api/notice';
import dayjs from 'dayjs';

const { TextArea } = Input;
const { RangePicker } = DatePicker;
const { confirm } = Modal;

/**
 * 公告管理页面（管理员）
 * 用于管理系统公告
 */
const NoticeManagement = () => {
    const [loading, setLoading] = useState(false);
    const [notices, setNotices] = useState([]);
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10,
        total: 0
    });
    const [visible, setVisible] = useState(false);
    const [currentNotice, setCurrentNotice] = useState(null);
    const [form] = Form.useForm();

    useEffect(() => {
        fetchNotices();
    }, [pagination.current, pagination.pageSize]);

    // 获取公告列表
    const fetchNotices = async () => {
        setLoading(true);
        try {
            const response = await getNotices({
                page: pagination.current,
                pageSize: pagination.pageSize
            });
            
            setNotices(response.data || []);
            setPagination({
                ...pagination,
                total: response.total || 0
            });
        } catch (error) {
            console.error('获取公告列表失败:', error);
            message.error('获取公告列表失败');
        } finally {
            setLoading(false);
        }
    };

    // 处理表格变化
    const handleTableChange = (pagination) => {
        setPagination(pagination);
    };

    // 新增公告
    const handleAdd = () => {
        setCurrentNotice(null);
        form.resetFields();
        setVisible(true);
    };

    // 编辑公告
    const handleEdit = (record) => {
        setCurrentNotice(record);
        form.setFieldsValue({
            ...record,
            valid_range: record.start_date && record.end_date 
                ? [dayjs(record.start_date), dayjs(record.end_date)]
                : undefined
        });
        setVisible(true);
    };

    // 删除公告
    const handleDelete = (record) => {
        confirm({
            title: '确认删除',
            icon: <ExclamationCircleOutlined />,
            content: '确定要删除这条公告吗？删除后将无法恢复。',
            onOk: async () => {
                try {
                    await deleteNotice(record.id);
                    message.success('删除成功');
                    fetchNotices();
                } catch (error) {
                    console.error('删除公告失败:', error);
                    message.error('删除公告失败');
                }
            }
        });
    };

    // 提交表单
    const handleSubmit = async () => {
        try {
            const values = await form.validateFields();
            
            // 处理日期范围
            const [startDate, endDate] = values.valid_range || [];
            
            const noticeData = {
                ...values,
                start_date: startDate ? startDate.format('YYYY-MM-DD') : null,
                end_date: endDate ? endDate.format('YYYY-MM-DD') : null
            };
            
            delete noticeData.valid_range;
            
            setLoading(true);
            if (currentNotice) {
                // 更新公告
                await updateNotice(currentNotice.id, noticeData);
                message.success('更新公告成功');
            } else {
                // 创建公告
                await createNotice(noticeData);
                message.success('创建公告成功');
            }
            
            setVisible(false);
            fetchNotices();
        } catch (error) {
            if (error.errorFields) {
                return; // 表单验证失败
            }
            console.error('保存公告失败:', error);
            message.error('保存公告失败');
        } finally {
            setLoading(false);
        }
    };

    // 表格列定义
    const columns = [
        {
            title: '标题',
            dataIndex: 'title',
            key: 'title',
            width: 250,
        },
        {
            title: '类型',
            dataIndex: 'type',
            key: 'type',
            width: 120,
            render: (type) => {
                const typeMap = {
                    'announcement': { color: 'blue', text: '公告' },
                    'notice': { color: 'green', text: '通知' },
                    'event': { color: 'purple', text: '活动' },
                    'policy': { color: 'orange', text: '政策' },
                    'other': { color: 'default', text: '其他' },
                };
                
                const { color, text } = typeMap[type] || { color: 'default', text: type };
                return <Tag color={color}>{text}</Tag>;
            },
        },
        {
            title: '发布人',
            dataIndex: 'publisher',
            key: 'publisher',
            width: 120,
        },
        {
            title: '发布日期',
            dataIndex: 'publish_date',
            key: 'publish_date',
            width: 120,
            defaultSortOrder: 'descend',
            sorter: (a, b) => new Date(a.publish_date) - new Date(b.publish_date),
        },
        {
            title: '有效期',
            key: 'valid_period',
            width: 200,
            render: (_, record) => {
                if (!record.start_date && !record.end_date) {
                    return '永久有效';
                }
                
                if (record.start_date && !record.end_date) {
                    return `${record.start_date} 起`;
                }
                
                if (!record.start_date && record.end_date) {
                    return `至 ${record.end_date}`;
                }
                
                return `${record.start_date} 至 ${record.end_date}`;
            },
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            width: 100,
            render: (status) => {
                const statusMap = {
                    'active': { color: 'green', text: '生效中' },
                    'inactive': { color: 'orange', text: '未生效' },
                    'expired': { color: 'red', text: '已过期' },
                    'draft': { color: 'default', text: '草稿' },
                };
                
                const { color, text } = statusMap[status] || { color: 'default', text: status };
                return <Tag color={color}>{text}</Tag>;
            },
        },
        {
            title: '操作',
            key: 'action',
            width: 150,
            render: (_, record) => (
                <Space size="middle">
                    <Button
                        type="link"
                        icon={<EditOutlined />}
                        onClick={() => handleEdit(record)}
                    >
                        编辑
                    </Button>
                    <Button
                        type="link"
                        danger
                        icon={<DeleteOutlined />}
                        onClick={() => handleDelete(record)}
                    >
                        删除
                    </Button>
                </Space>
            ),
        },
    ];

    return (
        <>
            <Card 
                title="公告管理" 
                extra={
                    <Button
                        type="primary"
                        icon={<PlusOutlined />}
                        onClick={handleAdd}
                    >
                        发布公告
                    </Button>
                }
            >
                <Table
                    columns={columns}
                    dataSource={notices}
                    rowKey="id"
                    loading={loading}
                    pagination={pagination}
                    onChange={handleTableChange}
                />
            </Card>

            {/* 公告表单弹窗 */}
            <Modal
                title={currentNotice ? '编辑公告' : '发布公告'}
                open={visible}
                onOk={handleSubmit}
                onCancel={() => setVisible(false)}
                confirmLoading={loading}
                width={700}
            >
                <Form
                    form={form}
                    layout="vertical"
                >
                    <Form.Item
                        name="title"
                        label="公告标题"
                        rules={[{ required: true, message: '请输入公告标题' }]}
                    >
                        <Input placeholder="请输入公告标题" maxLength={100} />
                    </Form.Item>
                    
                    <Form.Item
                        name="type"
                        label="公告类型"
                        rules={[{ required: true, message: '请选择公告类型' }]}
                    >
                        <Select placeholder="请选择公告类型">
                            <Select.Option value="announcement">公告</Select.Option>
                            <Select.Option value="notice">通知</Select.Option>
                            <Select.Option value="event">活动</Select.Option>
                            <Select.Option value="policy">政策</Select.Option>
                            <Select.Option value="other">其他</Select.Option>
                        </Select>
                    </Form.Item>
                    
                    <Form.Item
                        name="content"
                        label="公告内容"
                        rules={[{ required: true, message: '请输入公告内容' }]}
                    >
                        <TextArea rows={6} placeholder="请输入公告内容" />
                    </Form.Item>
                    
                    <Form.Item
                        name="publisher"
                        label="发布人"
                        rules={[{ required: true, message: '请输入发布人' }]}
                    >
                        <Input placeholder="请输入发布人" />
                    </Form.Item>
                    
                    <Form.Item
                        name="valid_range"
                        label="有效期"
                    >
                        <RangePicker style={{ width: '100%' }} />
                    </Form.Item>
                    
                    <Form.Item
                        name="status"
                        label="状态"
                        rules={[{ required: true, message: '请选择状态' }]}
                        initialValue="active"
                    >
                        <Select placeholder="请选择状态">
                            <Select.Option value="active">立即生效</Select.Option>
                            <Select.Option value="inactive">暂不生效</Select.Option>
                            <Select.Option value="draft">保存为草稿</Select.Option>
                        </Select>
                    </Form.Item>
                </Form>
            </Modal>
        </>
    );
};

export default NoticeManagement; 